package arithmetic.LeetCode;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 使用java里的函数快速实现缓存
 * @author jiangfeng on 2023/4/11
 */
public class LRUCache2  {

    public static void main(String[] args) {

        // ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
        //[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
        LRUCache2 lruCache = new LRUCache2(2);
        lruCache.put(1, 1);
        lruCache.put(2, 2);
        System.out.println(lruCache.get(1));
        lruCache.put(3, 3);
        System.out.println(lruCache.get(1));
        System.out.println(lruCache.get(2));
        System.out.println(lruCache.get(3));
        lruCache.put(4, 4);
        lruCache.put(5, 5);
        System.out.println(lruCache.get(3));
        System.out.println(lruCache.get(4));
        System.out.println(lruCache.get(4));
        System.out.println(lruCache.get(1));
        System.out.println(lruCache.get(1));
    }

    int capacity;
    HashMap<Integer,Integer> map;
    public LRUCache2(int capacity) {
        map =new LinkedHashMap(capacity,1f,true){
            @Override
            protected boolean removeEldestEntry(Entry eldest) {
                return size()>capacity;
            }
        };
        this.capacity=capacity;
    }


    public int get(int key) {
        Integer value = map.get(key);
        return value==null?-1:value.intValue();
    }

    public void put(int key, int value) {
        map.put(key,value);
    }
}
